package org.refresh.injectors;

import java.util.List;
import java.util.Map;

/******************************************************************************
 * Copyright (c) 2005, 2006 Jules White.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Jules White - initial API and implementation 
 ****************************************************************************/
public class BasicTemplateInjector implements TemplateInjector{

	public static final String DEFAULT_KEY = "value";
	
	private static BasicTemplateInjector instance_;
	
	public static BasicTemplateInjector getInstance(){
		if(instance_ == null){
			instance_ = new BasicTemplateInjector();
		}
		return instance_;
	}
	
	public static final String KEY_PREFIX = "\\$\\{[\\s]*";
	public static final String KEY_POSTFIX = "[\\s]*\\}";
	
	private BasicTemplateInjector(){}
	
	public String inject(String template, Object value){
		if(value instanceof Map){
			return injectMap((Map)value, template);
		}
		else if(value instanceof List){
			return injectListKey(DEFAULT_KEY, (List)value, template);
		}
		else {
			return injectObjectKey(DEFAULT_KEY, value, template);
		}
	}
	
	public String injectMap(Map values, String template){
		for(Object key : values.keySet()){
			Object value = values.get(key);
			if(value instanceof List){
				template = injectListKey(""+key, (List)value, template);
			}
			else{
				template = injectObjectKey(""+key, value, template);
			}
		}
		return template;
	}
	
	public String injectObjectKey(String key, Object value, String template){
		return template.replaceAll(KEY_PREFIX+key+KEY_POSTFIX, ""+value);
	}
	
	public String injectListKey(String key, List value, String template){
		String lval = null;
		if(value == null || value.size() == 0)
			lval = "[]";
		else
			lval = value.toString();
		return template.replaceAll(KEY_PREFIX+key+KEY_POSTFIX, lval);
	}
}
